<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="场地名称" prop="venueName">
        <el-input
          v-model="queryParams.venueName"
          placeholder="请输入场地名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="容纳人数" prop="capacity">
        <el-input
          v-model="queryParams.capacity"
          placeholder="请输入容纳人数"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-input
          v-model="queryParams.address"
          placeholder="请输入地址"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="价格/天" prop="price">
        <el-input
          v-model="queryParams.price"
          placeholder="请输入价格/天"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['reunion:venue:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['reunion:venue:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['reunion:venue:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['reunion:venue:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="venueList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="场地ID" align="center" prop="id" />
      <el-table-column label="场地名称" align="center" prop="venueName" />
      <el-table-column label="场地类型" align="center" prop="venueType" />
      <el-table-column label="容纳人数" align="center" prop="capacity" />
      <el-table-column label="地址" align="center" prop="address" />
      <el-table-column label="场地描述" align="center" prop="description" />
      <el-table-column label="场地图片列表，JSON数组格式" align="center" prop="images" width="100">
        <template slot-scope="scope">
          <image-preview v-for="(item,index) in jsonToString(scope.row.images).split(',') " :width="50" :height="50" :src="item" :key="index"> </image-preview>
<!--          <image-preview v-for="(item,index) in JSON.parse(stringToJson(scope.row.images))" :src="item" :key="index" :width="50" :height="50">-->

<!--          </image-preview>-->
        </template>
      </el-table-column>
      <el-table-column label="配套设施列表，包含图标、名称和描述的JSON数组" align="center" prop="facilities" />
      <el-table-column label="预订规则" align="center" prop="bookingRules" />
      <el-table-column label="使用须知" align="center" prop="usageNotes" />
      <el-table-column label="价格/天" align="center" prop="price" />
      <el-table-column label="状态：0-维护中，1-可用 2使用中" align="center" prop="status" >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 0" type="danger">维护中</el-tag>
          <el-tag v-else-if="scope.row.status === 1" type="success">可用</el-tag>
          <el-tag v-else-if="scope.row.status === 2" type="warning">使用中</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['reunion:venue:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['reunion:venue:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改场地对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="场地名称" prop="venueName">
          <el-input v-model="form.venueName" placeholder="请输入场地名称" />
        </el-form-item>
        <el-form-item label="容纳人数" prop="capacity">
          <el-input v-model="form.capacity" placeholder="请输入容纳人数" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="场地描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="场地类型" prop="venueType">
          <el-input v-model="form.venueType" placeholder="请输入场地类型" />
        </el-form-item>
        <el-form-item label="场地状态" prop="venueType">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="维护中" value="0"></el-option>
            <el-option label="可用" value="1"></el-option>
            <el-option label="使用中" value="2"></el-option>
          </el-select>
       <el-input v-model="form.status" placeholder="请输入场地类型" />
        </el-form-item>
        <el-form-item label="场地图片列表，JSON数组格式" prop="images">
          <image-upload v-model="form.images"/>
        </el-form-item>
        <el-form-item label="配套设施列表，包含图标、名称和描述的JSON数组" prop="facilities">
<!--          <el-input v-model="form.facilities" placeholder="请输入配套设施列表，包含图标、名称和描述的JSON数组" />-->
            <FacilitiesEditor v-model="form.facilities"></FacilitiesEditor>
        </el-form-item>
        <el-form-item label="预订规则" prop="bookingRules">
          <el-input v-model="form.bookingRules" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="使用须知" prop="usageNotes">
          <el-input v-model="form.usageNotes" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="价格/天" prop="price">
          <el-input v-model="form.price" placeholder="请输入价格/天" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listVenue, getVenue, delVenue, addVenue, updateVenue } from "@/api/reunion/venue";
import FacilitiesEditor from "@/components/FacilitiesEditor/index.vue";

export default {
  name: "Venue",
  components: {FacilitiesEditor},
  data() {
    return {
      images:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 场地表格数据
      venueList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        venueName: null,
        venueType: null,
        capacity: null,
        address: null,
        description: null,
        images: null,
        facilities: null,
        bookingRules: null,
        usageNotes: null,
        price: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        venueName: [
          { required: true, message: "场地名称不能为空", trigger: "blur" }
        ],
        venueType: [
          { required: true, message: "场地类型不能为空", trigger: "change" }
        ],
        capacity: [
          { required: true, message: "容纳人数不能为空", trigger: "blur" }
        ],
        address: [
          { required: true, message: "地址不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态：0-维护中，1-可用不能为空", trigger: "change" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        updateTime: [
          { required: true, message: "更新时间不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询场地列表 */
    getList() {
      this.loading = true;
      listVenue(this.queryParams).then(response => {
        console.log(response);
        this.venueList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        venueName: null,
        venueType: null,
        capacity: null,
        address: null,
        description: null,
        images: null,
        facilities: null,
        bookingRules: null,
        usageNotes: null,
        price: null,
        status: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加场地";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getVenue(id).then(response => {
        this.form = response.data;
        this.form.images = this.jsonToString(this.form.images);
        this.open = true;
        this.title = "修改场地";
      });
    },
    jsonToString(jsonData) {
      if (!jsonData) return '';
      try {
        // 如果输入是字符串，先解析成数组
        const arr = typeof jsonData === 'string' ? JSON.parse(jsonData) : jsonData;
        // 确保是数组
        if (Array.isArray(arr)) {
          return arr.join(',');
        }
        return '';
      } catch (e) {
        // 如果解析失败，返回空字符串
        return '';
      }
    },
    stringToJson(pathString) {
      if (!pathString) return '[]';
      // 将字符串按逗号分割成数组
      const pathArray = pathString.split(',');
      // 返回JSON字符串
      return JSON.stringify(pathArray);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          console.log(this.form)
          this.images=this.form.images
          // 检查images是否已经是JSON格式
          if (this.images) {
            try {
              // 尝试解析，如果是有效的JSON，则不需要再次转换
              JSON.parse(this.images);
              // 如果能成功解析，说明已经是JSON格式，不需要再次转换
            } catch (e) {
              // 如果解析失败，说明不是JSON格式，需要转换
              this.images = this.stringToJson(this.form.images);
            }
          } else {
            // 如果为空，设置为空数组的JSON字符串
            this.images = '[]';
          }
          this.form.images = this.images;
          if (this.form.id != null) {
            updateVenue(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addVenue(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除场地编号为"' + ids + '"的数据项？').then(function() {
        return delVenue(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('reunion/venue/export', {
        ...this.queryParams
      }, `venue_${new Date().getTime()}.xlsx`)
    },

    /**
     * 确保图片路径是正确的JSON格式
     * @param {String} images 图片路径字符串
     * @returns {String} 处理后的图片路径
     */
    getImageSrc(images) {
      if (!images) return '[]';
      try {
        // 尝试解析，如果是有效的JSON，则直接返回
        JSON.parse(images);
        return images;
      } catch (e) {
        // 如果解析失败，说明不是JSON格式，需要转换
        return this.stringToJson(images);
      }
    }
  }
};
</script>


